package com.tensquare.notice.listener;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.tensquare.entity.Result;
import com.tensquare.entity.StatusCode;
import com.tensquare.notice.netty.MyWebSocketHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;

import java.util.HashMap;

/**
 * @Author: xxx
 * @Date: 2022/11/13 21:34
 * @Description: 消息监听器
 */
public class SysNoticeListener implements ChannelAwareMessageListener {
    
    private static ObjectMapper mapper=new ObjectMapper();
    
    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        //获取用户的id,可以通过队列名称获取
        String queueName = message.getMessageProperties().getConsumerQueue();
        System.out.println("队列名称:"+queueName);
        String userId = queueName.substring(queueName.lastIndexOf("_") + 1);

        io.netty.channel.Channel wsChannel = MyWebSocketHandler.userChannelMap.get(userId);
        //判断用户是否在线
        if (wsChannel!=null){
            //如果连接不为空，则表示用户在线
            //封装返回的数据
            HashMap countMap = new HashMap<>();
            countMap.put("sysNoticeCount", 1);
            Result result=new Result(true, StatusCode.OK,"查询成功",countMap);
            //把数据通过webSocket连接主动推送到用户
            wsChannel.writeAndFlush(new TextWebSocketFrame(mapper.writeValueAsString(result)));
        }
        
    }
}
